package com.yao.demo4;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

/**
 * @Description 对象深拷贝工具类,流化对象
 * @author yaoym
 * @date 2018年5月30日 上午9:51:56
 * @version V1.0
 */
public class CloneUtil {

	public static <T extends Serializable> T clone(T obj) {
		T cloneObj = null;
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		try {
			// 写入流
			ObjectOutputStream obs = new ObjectOutputStream(out);
			obs.writeObject(obj);
			obs.close();

			// 分配新内存，将流对象生成新对象
			ByteArrayInputStream ios = new ByteArrayInputStream(out.toByteArray());
			ObjectInputStream ois = new ObjectInputStream(ios);

			// 返回生成的新对象
			cloneObj = (T) ois.readObject();
			ois.close();

		} catch (IOException | ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return cloneObj;
	}

}
